package com.example.ts_app_dart.plugins.custom_view

import com.example.ts_app_dart.MainActivity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.*
import io.flutter.plugin.common.PluginRegistry.Registrar

class CustomViewPlugin(mainActivity: MainActivity) : FlutterPlugin,
    MethodChannel.MethodCallHandler {
    private lateinit var channel: MethodChannel;

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        val messenger: BinaryMessenger = binding.binaryMessenger
        channel = MethodChannel(binding.binaryMessenger, "com.example/custom_channel")
        channel.setMethodCallHandler(this)

        binding.platformViewRegistry.registerViewFactory(
            "com.example/custom_view",
            CustomViewFactory(messenger),
        )
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    }

    // 保留旧版本的兼容 - 测试移除后不受影响
    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar) {
            registrar
                .platformViewRegistry()
                .registerViewFactory(
                    "com.example/custom_view",
                    CustomViewFactory(registrar.messenger())
                )
        }
    }

    private fun countTimeFun() {
        val timer = Timer()
        println("This is a fun")
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "getPlatform") {
            countTimeFun()
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else {
            result.notImplemented()
        }
    }
}